package userservicelogic

import (
	"context"
	"database/sql"
	"smile-sunshine-micorservice/rpc/User/db/crud"
	"time"

	"smile-sunshine-micorservice/rpc/User/internal/svc"
	"smile-sunshine-micorservice/rpc/User/pb/zipTako.com/SmileSunshine/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	UsersModel crud.UsersModel
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		UsersModel: crud.NewUsersModel(svcCtx.SqlConn, svcCtx.CacheConf),
	}
}

func (l *UpdateLogic) Update(in *user.UpdateUserRequest) (*user.UpdateUserResponse, error) {
	findOne, err := l.UsersModel.FindOne(l.ctx, in.UserId)
	if err != nil {
		return nil, err
	}
	findOne.Username = in.Username
	findOne.Email = in.Email
	findOne.Phone = sql.NullString{
		String: in.Phone,
		Valid:  in.Phone != "",
	}
	err = l.UsersModel.Update(l.ctx, findOne)
	if err != nil {
		return nil, err
	}

	return &user.UpdateUserResponse{
		Success: true,
		Message: "",
		User: &user.User{
			Id:        in.UserId,
			Username:  in.Username,
			Email:     in.Email,
			Phone:     in.Phone,
			CreatedAt: findOne.CreatedAt.Unix(),
			UpdatedAt: time.Now().Unix(),
		},
	}, nil
}
